<?php
/**
 * Created by IntelliJ IDEA.
 * Date: 2019-06-06
 * Time: 10:34
 */
if (!defined('admin')) {
    exit();
}
$icon = getPost("icon", false);
$sort = getPost("sort", false);
$name = getPost("name", false);
$file = getPost("file", false);
$dfile = getPost("dfile", false);
$do = getPost("ex", false);

//"file": "zh.json",
//    "icon": "",
//    "name": "zh",
//    "sort": 100

if ($file) {
    if (strtolower(substr($file, -5)) != ".json") {
        $file .= ".json";
    }
}

$settingfile = AppDir . "languages/setting.json";

if ($do == "copy") {
    if (strtolower(substr($dfile, -5)) != ".json") {
        $dfile .= ".json";
    }
    if ($file !== false && $dfile !== false) {
        if (!file_exists(AppDir . "languages/" . $dfile)) {
            if (copy(AppDir . "languages/" . $file, AppDir . "languages/" . $dfile)) {
                //复制成功
            } else {
                exit(resp_error_json("复制失败，请重试"));
            }
        } else {
            exit(resp_error_json("目标文件已存在，请输入另外的文件名"));
        }
    } else {
        exit(resp_error_json("请选择要复制的文件及输入复制后的文件名称"));
    }
} else if ($do == "add") {
    if (!file_exists(AppDir . "languages/" . $file)) {
        $langContent = <<<JSON
{
  "Generic" : {
    "Welcome": "Welcome",
    "Hello": "Hello %s!",
    "submit": "submit"
  }
}
JSON;

        if (file_put_contents(AppDir . "languages/" . $file, $langContent) !== false) {
            //成功
            exit(resp_success_json("创建成功"));
        } else {
            exit(resp_error_json("创建失败，请重试"));
        }

    } else {
        exit(resp_error_json("目标文件已存在，请输入另外的文件名"));
    }
}

$jdb = json_decode(file_get_contents($settingfile), 1);
if ($file) {
    if ($do == "del") {
        //删除文件
        unlink(AppDir . "languages/" . $file);
    }
    $had = false;
    foreach ($jdb as $i => $item) {
        if ($item['file'] == $file) {
            if ($do == "del") {
                //删除此语言的配置
                unset($jdb[$i]);
            } else {
                if ($icon !== false) {
                    $jdb[$i]['icon'] = $icon;
                }
                if ($sort !== false) {
                    $jdb[$i]['sort'] = $sort;
                }
                if ($name !== false) {
                    $jdb[$i]['name'] = $name;
                }
            }

            $had = true;
            break;
        }
    }

    if (!$had && $do != "del") {
        if (file_exists(AppDir . "languages/" . $file)) {
            $jdb[] = array("file" => $file, "name" => $name, "sort" => $sort, "icon" => $icon);
        }
    }

    file_put_contents($settingfile, json_encode($jdb));

    exit(resp_success_json("已保存"));
}
exit(resp_error_json("不存在该文件"));

